package utils

import (
	"encoding/hex"
	"errors"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"regexp"
	"strings"
)

var uuidRegex *regexp.Regexp = regexp.MustCompile(`^\{?([a-fA-F0-9]{8})-?([a-fA-F0-9]{4})-?([a-fA-F0-9]{4})-?([a-fA-F0-9]{4})-?([a-fA-F0-9]{12})\}?$`)

type UUID [16]byte

func (x *UUID) String() string {
	return fmt.Sprintf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
		x[0], x[1], x[2], x[3], x[4],
		x[5], x[6],
		x[7], x[8],
		x[9], x[10],
		x[11], x[12], x[13], x[14], x[15])
}

func (x *UUID) Rand() *UUID {
	NonceBuffer((*x)[:])
	x[6] = (x[6] & 0x0F) | 0x40
	x[8] = (x[8] & 0x3F) | 0x80
	return x
}

func (x *UUID) Hex(args ...interface{}) string {
	return HexEncoder((*x)[:], args...)
}

func (x *UUID) Format(s string) (err error) {
	if len(s) >= 36 {
		if parts := uuidRegex.FindStringSubmatch(s); nil != parts {
			slice, _ := hex.DecodeString(strings.Join(parts[1:], ""))
			copy((*x)[:], slice)
		}
	}
	return errors.New("Invalid string format")
}

func UuidCreate() string {
	token := uuid.NewV4()
	return token.String()
}

//短uuid创建
func SUuidCreate() string {
	token := UuidCreate()
	return strings.ReplaceAll(token, "-", "")
}
